var appPath = getAppPath();	
var myDomain = 'http://7xogoq.com1.z0.glb.clouddn.com';
var validFile = false;
var uploader = null;
var jsonData = null;

$(function(){
	initJspGrid();
	
	// 初始化 视频播放 点击红叉  停止播放
	$('#playVideoDlg').window({
	       onBeforeClose:function(){ 
	    	   var myVideo = document.getElementsByTagName('video')[0];
	    	   myVideo.pause(); // 暂停视频 播放
	       }
	});
});

// 自定义动画列表初始化
function initJspGrid(){
	
	$('#imageGrid').datagrid({
	    url:appPath + "/yjxCust/getCustAniInfo.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
		checkbox:false,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'ani_id',title:'图像ID',width:25,align:'center',sortable:false}, 
	        {field:'ani_type',title:'图像类型',width:30,align:'center',sortable:true,
	        	formatter:function(value,rowData,rowIndex){
	        		var ret = 'Non';
	        		switch(value){
	        		case 10: ret = 'AE图像';break;
	        		case 20: ret = 'C4D图像'; break
	        		}
	        		return '<span style="color:#B22222;">'+ret+'</span>';
	        	}
	        },
	        {field:'priv',title:'场景',width:30,align:'center',sortable:true,
	        	formatter:function(value,rowData,rowIndex){
	        		var ret = '共通的';
	        		switch(value){
	        		case 0: ret = '<span style="color:#8FBC8F;">共通的</span>';break;
	        		case 1: ret = '<span style="color:#8E8E38;">私有的</span>'; break
	        		}
	        		return ret;
	        	}
	        },
	        {field:'user_id',title:'用户ID',width:25,align:'center',sortable:true},
	        {field:'nickname',title:'用户昵称',width:40,align:'center',sortable:true},
	        {field:'ani_name',title:'图像名',width:50,align:'left',sortable:true},
	        {field:'url',title:'资源地址',width:60,align:'left',sortable:false,
	        	formatter:function(url, rowData, rowIndex){
	        		var retUrl = '';
	        		if (rowData.url) {
	        			var thumb = JSON.parse(rowData.thumbs);// 视频动画封面图
	        			retUrl = '<a href="javascript:void(0)" onclick="playVideo(\''+thumb+'\',\''+rowData.url+'\')">'
	        				+ rowData.url.replace('http://itbour-back.oss-cn-hangzhou.aliyuncs.com','')
	        				+ '</a>';
	        		}
	        		return retUrl;
	        	}
	        },  
	        {field:'tmplJson',title:'TmplJson',width:30,align:'center',sortable:true,
	        	formatter:function(value,rowData,rowIndex){
	        		return '<a href="javascript:void(0)" onclick="showTmplJson('+rowData.ani_id+')">查看</a>';
	        	}
	        },
	        {field:'tmplSet',title:'TmplSet',width:30,align:'center',sortable:true,
	        	formatter:function(value,rowData,rowIndex){ // c.tmpl_json, c.tmpl_set
	        		return '<a href="javascript:void(0)" onclick="showTmplSet('+rowData.ani_id+')">查看</a>';
	        	}
	        },
	        {field:'duration',title:'时长',width:30,align:'center',sortable:true},
	        {field:'create_time',title:'创建时间',width:60,align:'center',sortable:true},
	        {field:'update_time',title:'修改时间',width:60,align:'center',sortable:true}
	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:true,
		toolbar:[
		{
			text:'添加动画',
			iconCls:'icon-add',
			handler:function(){
				showAddInfo();
			}
		},
		{
			text:'删除动画',
			iconCls:'icon-no',
			handler:function(){
				delCustInfo();
			}
		}
		]
	    
	});
}

//播放视频资源
function playVideo(thumb,videoUrl){
	$('#playVideoDlg').window({
		title:'视频播放',
		iconCls:'icon-tip',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	if (!videoUrl){
		return $.messager.alert('警告','该视频资源暂无..','warning');
	}
	
	$('#playVideoDlg').window('move',{top:20,left:200});
	$('#playVideoDlg').window('open');
	var retUrl = '<a href="'+thumb+'" target ="_blank" '
	+ '<div style="display:table;text-align:center;height:150px;width:100%">'
	+ '<span style="display:table-cell;vertical-align:middle">'
	+ '<img src="' +thumb+'?x-oss-process=image/resize,m_lfit,h_146,w_250'
	+ '" style="display:inline;max-height:150px;max-width:400px"></span></div></a>';
	
	$("#videoThumb").html(retUrl);
	var htm = '<video style="margin-left:20px;height:270px;" controls="controls" preload="auto" poster="'+thumb+'" src="'+videoUrl+'"></video>';
	$("#viderUrl").html(htm);
}

// 查看TmplJson数据 图像ID
function showTmplJson(ani_id){
	$("#tmplJsonTxt").val('');
	$.loading(true);
	var url = appPath + "/yjxCust/getOneCustInfo.action?aniId="+ani_id;// 请求获取tmplJson数据
	$.post(url,function(ret){
		if (ret){
			$.loading(false);
			var info = ret[0];
			$("#tmplJsonTxt").val(info.tmpl_json);
		} else {
			$.loading(false);
		}
	});
	$('#tmplJsonDlg').window({
		title:'TmplJson内容信息',
		iconCls:'icon-tip',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	$('#tmplJsonDlg').window('move',{top:20,left:20});
	$('#tmplJsonDlg').window('open');
}


// 查看TmplSet数据
function showTmplSet(ani_id){
	$("#tmplSetTable").html('');
	var url = appPath + "/yjxCust/getOneCustInfo.action?aniId="+ani_id;// 请求获取tmplJson数据
	$.post(url,function(ret){
		var json = ret[0].tmpl_set;
		json = JSON.parse(json);
		var dur = json[1] || '0'; // 模板默认时长
		var fontUpCnt = json[2] || '0'; // 模板默认可支持修改的文字个数
		var imgUpCnt = json[3] || '0'; // 模板默认可支持修改的图片个数
		var ObjBase = json[4] || '0'; //  AE可替换对象转换成ObjBase类型后的数组
		var fiveCnt = json[5] || '0';// 图片ID  对应图片地址
		
		var htl = '<tr><td class="queryTitle" style="width:140px;color:red;">模板默认时长:</td><td class="queryContent" style="width:400px;">'+dur+'</td></tr>'+
		'<tr><td class="queryTitle" style="width:140px;color:red;">可修改文字个数:</td><td class="queryContent" style="width:400px;">'+fontUpCnt+'</td></tr>'+
		'<tr><td class="queryTitle" style="width:140px;color:red;">可修改图片个数:</td><td class="queryContent" style="width:400px;">'+imgUpCnt+'</td></tr>'+
		'<tr><td class="queryTitle" style="width:140px;color:red;">OBJBase类型数组:</td><td class="queryContent""><textarea rows="6" cols="50">'+JSON.stringify(ObjBase)+'</textarea></td></tr>'+
		'<tr><td class="queryTitle" style="width:140px;color:red;">图片对应地址:</td><td style="width:400px;"><div style="border:0;width:190px;float:left;" id="five1"></div><div style="border:0;width:190px;float:left;" id="five2"></div></td></tr>';
		$("#tmplSetTable").html(htl);
		
		// 显示 两列图片
		var tmpHtl = '';//  左边
		var tmpHtl2 = '';// 右边
		var cnt = 0;// 定义计数器
		if (fiveCnt){ // 	tmpl_set 里面的图片展示
			for(var js2 in fiveCnt){// <input type="text" value= "'+fiveCnt[js2]+'"></input>
				cnt++;
				if ((cnt%2) == 0){ // 如果是偶数  则显示在左边DIV
					tmpHtl = tmpHtl + '<tr><td class="queryTitle" style="width:60px;color:red;">ID'+js2+':</td>'+
					'<td class="queryContent">'+
					'<a href="' + fiveCnt[js2] + '" target="_blank">'
					+ '<div style="display:table;text-align:center;height:110px;width:100%">'
					+ '<span style="display:table-cell;vertical-align:middle">'
					+ '<img src="' +fiveCnt[js2]+'?x-oss-process=image/resize,m_lfit,h_120,w_100'
					+ '" style="display:inline;max-height:100px;max-width:100px"></span></div></a></td></tr>';
				} else {
					tmpHtl2 = tmpHtl2 + '<tr><td class="queryTitle" style="width:60px;color:red;">ID'+js2+':</td>'+
					'<td class="queryContent">'+
					'<a href="' + fiveCnt[js2] + '" target="_blank">'
					+ '<div style="display:table;text-align:center;height:110px;width:100%">'
					+ '<span style="display:table-cell;vertical-align:middle">'
					+ '<img src="' +fiveCnt[js2]+'?x-oss-process=image/resize,m_lfit,h_120,w_100'
					+ '" style="display:inline;max-height:100px;max-width:100px"></span></div></a></td></tr>';
				}
			}
		}
		$("#five1").html(tmpHtl);
		$("#five2").html(tmpHtl2);
		
	});
	
	$('#tmplSetDlg').window({
		title:'TmplSet内容信息',
		iconCls:'icon-tip',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	$('#tmplSetDlg').window('move',{top:20,left:20});
	$('#tmplSetDlg').window('open');
}

function showAdd(){
	$('#selectTypeDlg').dialog({
		buttons:[
			{text:'确定',iconCls:"icon-ok",handler:function(){
				var memberType=$("#selctMemberType").combobox("getValue");
				if(!memberType||memberType.length<=0){
					$.messager.alert('提示信息','请选择会员类型！','warning');
					return;
				}
				$('#selectTypeDlg').dialog('close');
				showAddInfo();
			}},
			{text:'取消',iconCls:"icon-cancel",handler:function(){
				$('#selectTypeDlg').dialog('close');
			}}
		]
	});
	$('#selectTypeDlg').dialog('open');
	//showAddInfo();
}

//重置用户密码
function resetPassword(){
	var selectMember=$("#imageGrid").datagrid("getSelected");
	if(!selectMember){
		$.messager.alert('提示信息','请选择要重置密码的会员！','warning');
		return;
	}
	var url = appPath+"/member/memberInfo_reset.do?memberId="+selectMember.memberId;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','密码重置成功，重置后的密码为123456','info');
		}
	});
}

/*	添加自定义动画
 */
function showAddInfo() {
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}
	
	
	$('#imgUploadForm').form('clear');
	$("#editBtn").hide();
	$("#imgUploadTable").show();
	$("#addDlgBtn").hide();// 先隐藏
	clearUploadList();
	$("#submitType").val("save");
	$('#addDlg').window({
		title:'上传自定义图像',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	 $("input[type=file]").change(function(e){
		 var files = $('input[name="jsonFile"]').prop('files');//获取到文件列表
		 if(files.length == 0){
			 $.messager.alert('提示信息','请选择动画JSON文件','warning');
		   return;
		 }else{
		   var reader = new FileReader();//新建一个FileReader
		   reader.readAsText(files[0], "UTF-8");//读取文件 
		   reader.onload = function(evt){ //读取完文件之后会回来这里
		   if (jsonData){ // 如果不为空 赋值为空
			   jsonData = '';
		   }
		   jsonData = evt.target.result;
		     if (isJSON(jsonData)){
		    	 jsonData = JSON.parse(jsonData);
		    	 $("#addDlgBtn").show('slow');
		     } else{
		    	 $.messager.alert('提示信息','请选择动画JSON文件','warning');
		     }
		   }
		 }
	 });
	 

	$('#addDlg').window('move',{top:20,left:20});
	$('#addDlg').window('open');
	
	//initUploader();
	initOSS();
}

// 判断是否是JSON文件
function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj=JSON.parse(str); // 从字符串中解析出 json对象
            if(str.indexOf('{')>-1){
                return true;
            }else{
                return false;
            }

        } catch(e) {
            console.log(e);
            return false;
        }
    }
    return false;
}

function isImage(url) {
    var res, suffix = "";
    var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"];
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;

    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = imageSuffixes.length; i < l; i++) {
        if (suffix === imageSuffixes[i]) {
            return true;
        }
    }
    return false;
}

function initUploader() {
	if (uploader) {
		return;
	}
	
	uploader = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: 'pickImgFile',
        //container: 'container',
        //drop_element: 'container',
        max_file_size: '100mb',
        flash_swf_url: appPath + '/js/qiniu/plupload/Moxie.swf',
        dragdrop: false,
        chunk_size: '4mb',
        uptoken_url: appPath+"/itbImg/getUpToken.action",
        //uptoken: data.uptoken,
        domain: myDomain,
        // downtoken_url: '/downtoken',
        // unique_names: true,
        save_key: true,// 自定义文件名
        // x_vars: {
        //     'id': '1234',
        //     'time': function(up, file) {
        //         var time = (new Date()).getTime();
        //         // do something with 'time'
        //         return time;
        //     },
        // },
        auto_start: false,//true
        init: {
            'FilesAdded': function(up, files) {
                $('#uploadMsg').hide();
                
                var fileCnt = up.files.length;
                if (fileCnt > 1) {
                	up.splice(0, fileCnt-1);
                }
                
                var fileName = up.files[0].name;
                $('#imgFileNm').val(fileName);
                if (Qiniu.isImage(fileName)) {
                	validFile = true;
                } else {
                	validFile = false;
                	setMsg("red", "请选择图像文件！");
                }
                /*plupload.each(files, function(file) {
                	$('#imgFileNm').val(file.name);
                    var progress = new FileProgress(file, 'fsUploadProgress');
                    progress.setStatus("等待...");
                    progress.bindUploadCancel(up);
                });*/
            },
            'BeforeUpload': function(up, file) {
                /*var progress = new FileProgress(file, 'fsUploadProgress');
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                if (up.runtime === 'html5' && chunk_size) {
                    progress.setChunkProgess(chunk_size);
                }*/
            },
            'UploadProgress': function(up, file) {
            	setMsg("green", file.name + ' 上传中...');
            	
               /* var progress = new FileProgress(file, 'fsUploadProgress');
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                progress.setProgress(file.percent + "%", file.speed, chunk_size);*/
            },
            'UploadComplete': function() {
            	//$('#uploadMsg').show();
            },
            'FileUploaded': function(up, file, info) {
            	var retInfo = $.parseJSON(info);
            	addImage(file.name, myDomain+'/'+ retInfo.key);
            	
            	setMsg("green", file.name + ' 上传成功！');

                /*var progress = new FileProgress(file, 'fsUploadProgress');
                progress.setComplete(up, info);*/

//                $.ajax('./uptoken',{
//                    async: false
//                }).done(function(data){
//                    $.extend(info, data);
//                    progress.setComplete(up, info);
//                }).error(function(){
//                    console.log('获取下载token失败');
//                });

            },
            'Error': function(up, err, errTip) {
            	setMsg("red", errTip);

                var progress = new FileProgress(err.file, 'fsUploadProgress');
                progress.setError();
                progress.setStatus(errTip);
            }
                // ,
                // 'Key': function(up, file) {
                //     var key = "";
                //     // do something with key
                //     return key
                // }
        }
    });
}

/* 删除自定义动画
 */
function delCustInfo(){
	var selectItem=$("#imageGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','选择需要删除的图像','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认删除", function (r) {  
        if (r) { 
			var ids = "";
			$.each(selectItem, function(index, item){
				ids = ids + item.ani_id + ",";
			});
			console.log(ids);
			var url = appPath+"/yjxCust/delCustAniInfo.action?ids="+ids;
			$.post(url,function(data){
				if(data=="ok"){
					$.messager.alert('提示信息','删除成功','info');
					doQuery();
				} else {
					$.messager.alert('提示信息','删除失败','warning');
				}
			});
        }
	});
}


// 确认提交添加 自定义图像
function doUPload(){
		var tmpl_json = JSON.stringify(jsonData);
		var aniName = $("#aniName").val();
		if (aniName == null || aniName.length<=0){
			$.messager.alert('提示信息','请填写图像名称！','info');
			return;
		}
		if (jsonData == null || jsonData.length<=0){
			$.messager.alert('提示信息','请选择JSON图像文件','info');
			return;
		}	
		if (document.getElementById("bName")){
		$.messager.confirm('确认','是否确定提交？',function(r){
			if (r){
				$.loading(true);
				var duration = (jsonData.op-jsonData.ip)/jsonData.fr;
				var firUrl = 'http://192.168.1.250:3000/design/parseInfoFromAEJson';
				var data1 = {
						"userId" : g_userId,
						"ltData" : tmpl_json
				};
				var tmplSet = '';
				
				$.post(firUrl,data1,function(ret){
					if (ret.success == 1){
						tmplSet = ret.data;
						var secdUrl = 'http://192.168.1.250:3000/design/createVideoForAEJson';
						var data2 = {
							"userId" : g_userId,
							"ltData" : tmpl_json
						};
						var viUrl = ''; // 视频地址
						var thumb_v = '';// 预览视频地址
						var thumb = '';// 预览图 地址
						$.post(secdUrl,data2,function(ret){
							  if (ret.success === 1){
									viUrl = ret.data.video;
									thumb_v = ret.data.thumb;
									thumb = ret.data.preview;
									var url = appPath + '/yjxCust/addCustAniInfo.action';
									var data3 = {
											'custAni.ani_name' :aniName,
											'custAni.tmpl_json' :tmpl_json,
											'custAni.tmpl_set' :tmplSet,
											'custAni.url' :viUrl,
											'custAni.thumb_v' :thumb_v,
											'custAni.thumbs' :thumb,
											'custAni.duration' : duration
									};
									$.post(url,data3,function(ret){
										if (ret == 'ok'){
											$.loading(false);
											$('#addDlg').window('close');
											$.messager.alert('提示信息','提交成功','info');
											jsonData = '';
										} else {
											$.loading(false);
											$.messager.alert('提示信息','提交失败','error');
											$('#addDlg').window('close');
											jsonData = '';
										}
									});	
							  } else {
								  $.loading(false);
								  $.messager.alert('警告信息','error:'+ret.msg,'error');
							  }
						});
					} else {
						$.loading(false);
						$.messager.alert('警告信息','提交'+ret.msg+'失败','warning');
					}
				});
				
			} else {
				$.loading(false);
			}	
		});
	} else {
		$.messager.alert('警告信息','请上传适合的图片!','warning');
	}
}

/** 
 * 增加三个字段 url(完整视频url地址) thumb_v(抽帧的预览视频url)  thumbs(预览用的缩略图)
 * 接口获取  tmpl_set 内容
 * 从bodymovin的json文件解析出数据 
 * 用于设计师设计上传AE文件后，解析数据，方便在编辑器中使用
 * 参数：userId
 * 参数：itData：   Lottie文档json数据, 必需存在
 * 参数：It_ver：    ［保留］版本号
 * 参数：w:          宽
 * 参数：h:          高
 * 参数：rate_num：  帧率的分子，例如 10
 * 参数：rate_den：  帧率的分母，例如 1
 * API: design/parseInfoFromAEJson
 * http://192.168.31.100:3000/design/parseInfoFromAEJson // 二师兄电脑ip服务
 */
function getTmplJson(tmpl_json,callback){
	var firUrl = 'http://192.168.31.100:3000/design/parseInfoFromAEJson';
	var data1 = {
			"userId" : g_userId,
			"ltData" : tmpl_json
	};
	var tmpl_set = '';
	$.ajax({ 
		  type: 'POST', 
		  url: firUrl, 
		  data: data1, 
		  success: function(ret){
			  if (ret.success == 1){
					tmpl_set = ret.data;
				}
		  }, 
		  dataType: "json", 
		  async:false 
	}); 
	return tmpl_set;
//	$.post(firUrl,data1,{}function(ret){
//		if (ret.success == 1){
//			tmpl_set = ret.data;
//		} else {
//			return tmpl_set;
//		}
//	});
}



/** author : kris
 * 根据bodymovin的json文件生成视频
 * 用于设计师设计上传AE文件后，生成mp4预览视频
 * 参数：userId
 * 参数：lt_data:     Lottie文档json数据, 必需存在
 * 参数：lt_ver:      ［保留］版本号
 * 参数：w:            宽
 * 参数：h:            高
 * 参数：daudio:      ［保留］默认音频的路径（必需为aac格式）
 * 参数：thumb_video_frames: [可选]生成预览视频的帧的数组的json，例如 "[1,4,9]"
 * 参数：thumb_image_frame:  [可选]生成预览图的帧，例如，3
 * 参数：rate_num:  帧率的分子，例如 10
 * 参数：rate_den:  帧率的分母，例如 1
 * callback: {video:'完整视频.mp4', thumb:'预览视频.mp4', preview:'预览图.jpg'}
 * API: design/createVideoForAEJson
 */
function getVidUrl(tmpl_json){
	var secdUrl = 'http://192.168.31.100:3000/design/createVideoForAEJson';
	var data2 = {
		"userId" : g_userId,
		"ltData" : tmpl_json
	};
	var viUrl = ''; // 视频地址
	var thumb_v = '';// 预览视频地址
	var thumb = '';// 预览图 地址
	$.ajax({ 
		  type: 'POST', 
		  url: secdUrl, 
		  data: data2, 
		  success: function(ret){
			  if (ret.success === 1){
					viUrl = ret.data.video;
					thumb_v = ret.data.thumb;
					thumb = ret.data.preview;
			  }
		  }, 
		  dataType: "json", 
		  async:false 
	}); 
	
	return {'viUrl':viUrl,'thumb_v':thumb_v,'thumb':thumb};
//	$.post(secdUrl,data2,function(ret){
//		if (ret.success === 1){
//			viUrl = ret.data.video;
//			thumb_v = ret.data.thumb;
//			thumb = ret.data.preview;
//			return {'viUrl':viUrl,'thumb_v':thumb_v,'thumb':thumb};
//		} else {
//			return {'viUrl':viUrl,'thumb_v':thumb_v,'thumb':thumb};
//		}
//	});
}

//  获取tmpl_set
function getTmpl_set(json){
    var tmpl_set = {};
    //获取自定义动画时长
    var duration = (json.op-json.ip)/json.fr;
    var imgNumber = json.op-json.ip;
    var textNumber = 0;
    if(json.layers && json.layers.length>0){
        for(var i=0;i<json.layers.length;i++){
            var item = json.layers[i];
            if(item.ty == 5 && (item.nm.indexOf("可替换")>=0)){
                textNumber++;
            }
        }
    }
    tmpl_set["1"] = duration;
    tmpl_set["2"] = textNumber;
    tmpl_set["3"] = imgNumber;
    return {tmpl_set:tmpl_set,dur:duration};
}


//   处理获取到的自定义动画(将一上传的图片oss地址存入到json的assets中)
function storeImgUrlFromJson(data,file,url){
    // file中的name为原始的图片名称 用于找到json中图片资源对应的位置
    // url为图片的oss地址
    // json为自定义动画导出的json
    for(var i=0;i<data.assets.length;i++){
        var item = data.assets[i];
        if(item.p == file.name ){
            item.url = url;
        }
    }
   return data;
}

/* 开始上传图片
 */
function doPostData(){
	if (validFile && uploader) {
		uploader.start();
	} else {
		setMsg("red", "请选择图像文件！");
	}
}

/**
 * 关闭对话框
 */
function cancelPostData(){
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}
	
	$('#addDlg').window('close');
}

function setMsg(color, msg) {
	$('#msgTxt').css("color", color);
	$('#msgTxt').val(msg);
	$('#uploadMsg').show();
}

/*  获取请求信息
 */
function getQueryParam(){
	var queryObject = {};
	var findUserId = $("#queryUserId").val();// 用户ID
	var findAniId=$("#queryAniId").val();// 图像ID
	var findName = $("#queryName").val();// 图像名称
	var findPri = $("#queryPri").combobox('getValue');
	if(findUserId&&findUserId.length>0) queryObject.findUserId = findUserId; // 用户ID
	if(findName&&findName.length>0) queryObject.findName = findName;// 图像名称
	if(findAniId&&findAniId.length>0) queryObject.findAniId = findAniId;// 图像ID
	if(findPri) queryObject.findPri = findPri;// 场景分类
	return queryObject;
}

/*  查询数据
 */
function doQuery(){
	$("#imageGrid").datagrid('unselectAll');
	$("#imageGrid").datagrid('load',getQueryParam());
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

function fmtHotFlag(value, rowData, rowIndex){
	if(rowData.hotFlag==1)return "是";
	return "否";
}





// ############### FOR OSS UPLOAD START ###############
//var accessid= '';
//var accesskey= '';
//var uploadHost = 'http://itbour-back.oss-cn-hangzhou.aliyuncs.com';

var g_object_name = ''; // 
var dtNow = Date.parse(new Date()); //Date.parse(new Date())/1000;

//var policyText = {
//"expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
//"conditions": [
//  ["content-length-range", 0, 104857600] // 设置上传文件的大小限制
//]
//};
//var policyJsonStr = JSON.stringify(policyText);
//var policyBase64 = Base64.encode(policyJsonStr);
//var message = policyBase64;
//var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true });
//var signature = Crypto.util.bytesToBase64(bytes);

var OSS_PARAM = {
	expire: 0,
	uploadHost: '',
	accessKeyId: '',
	policyBase64: '',
	signature: '',
	flg: false
};

function randomString(len) {
	len = len || 20;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
	var maxLen = chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += chars.charAt(Math.floor(Math.random() * maxLen));
    }
	return str;
}

function getSuffix(filename) {
    var pos = filename.lastIndexOf('.');
    var suffix = '';
    if (pos != -1) {
        suffix = filename.substring(pos);
    }
    return suffix;
}

function calculate_object_name(filename) {
	var now = new Date(); 
	var nowStr = now.format("yyyy/MM/dd/hhmmssS_");
    g_object_name = "image/U"+g_userId+"/"+nowStr + randomString(20);
}

function set_upload_param(up, filename, ret) {
    
	// 判断当前expire是否超过了当前时间,如果超过了则重新取
	dtNow = Date.parse(new Date());//  Date.parse(new Date())/1000
	OSS_PARAM.flg = false;
    if (OSS_PARAM.expire < dtNow + 5000) {// 5s
    	var url = appPath+"/itbImg/getOSSToken.action";
        $.get(url, function(data){  
    		if (data && data.signature) { 
    			OSS_PARAM.expire = data.expire;
    			OSS_PARAM.uploadHost = data.uploadHost;
    			OSS_PARAM.accessKeyId = data.accessKeyId;
    			OSS_PARAM.policyBase64 = data.policyBase64;
    			OSS_PARAM.signature = data.signature;
    			OSS_PARAM.flg = true;
    			
    			doUpStart(up, filename, ret);
            } else {
            	$.messager.alert('提示信息','上传异常, 请重新尝试!','info');
            }  
        });
    } else {
    	doUpStart(up, filename, ret);
    }
}

function doUpStart(up, filename, ret){
	if (filename && filename != '') {
		calculate_object_name(filename);
    }
    var new_multipart_params = {
        'key' : g_object_name,
        'policy': OSS_PARAM.policyBase64,
        'OSSAccessKeyId': OSS_PARAM.accessKeyId, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': OSS_PARAM.signature,
    };

    up.setOption({
        'url': OSS_PARAM.uploadHost,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function clearUploadList() {
	$(".upload_progress_bar").remove();
	$(".upload_progress").remove();
	$(".upload_file_info").remove();
}

function initOSS() {
	if (uploader) {
		return;
	}

	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selFiles', 
	    //multi_selection: false,
		//container: document.getElementById('container'),
		//flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		//silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
	    url : 'http://oss.aliyuncs.com',

		init: {
			PostInit: function() {
				document.getElementById('postFiles').onclick = function() {
		            set_upload_param(uploader, '', false);
		            return false;
				};
			},

			FilesAdded: function(up, files) {
				clearUploadList();
				$('#uploadMsg').hide();
				
				var delLen = (up.files.length>=files.length)?(up.files.length-files.length):up.files.length;
				up.splice(0,delLen);
				
				var bAllOk = true;
				plupload.each(files, function(file) {
					if (isImage(file.name)) {
						// add file info list
						document.getElementById('ossfile').innerHTML += 
	                    	'<div id="' + file.id + '" class="upload_file_info">'
	                    	+ file.name + ' (' + plupload.formatSize(file.size) + ') <b id="bName"></b>'
	                    	+ '<div class="upload_progress">'
	                    	+ '<div class="upload_progress_bar" style="width: 0%">'
	                    	+ '</div></div></div>';
					} else {
						bAllOk = false;
						var ngFile = up.getFile(file.id);
						if (ngFile) {
							up.removeFile(ngFile);
						}
					}
				});
				
				if (!bAllOk) {
					setMsg("red", "已过滤非图像文件！");
				}     
			},

			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },

			UploadProgress: function(up, file) {
				var d = document.getElementById(file.id);
				d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
	            var prog = d.getElementsByTagName('div')[0];
				var progBar = prog.getElementsByTagName('div')[0];
				progBar.style.width= 2*file.percent+'px';
				progBar.setAttribute('aria-valuenow', file.percent);
				
				setMsg("green", file.name + ' 上传中...');
			},

			FileUploaded: function(up, file, info) {
	            if (info.status == 200) {
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功:' + g_object_name;
//	            	addImage(file.name, OSS_PARAM.uploadHost+'/'+ g_object_name);
	            	jsonData = storeImgUrlFromJson(jsonData,file,OSS_PARAM.uploadHost+'/'+ g_object_name);
	            	setMsg("green", '上传成功!');
	            	$("#editBtn").show('slow');
	            }
	            else {
	            	setMsg("red", '上传出错！');
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
	            }
			},

			Error: function(up, err) {
//				document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
				setMsg("red", err.response);
			}
		}
	});
	
	uploader.init();
}
//############### FOR OSS UPLOAD END ###############